const { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } = require('docx');
const fs = require('fs');

class DocumentExporter {
  constructor() {
    this.defaultStyles = {
      font: '微软雅黑',
      fontSize: 24, // 12pt in half-points
      lineSpacing: 360, // 1.5倍行距
      paragraphSpacing: 200
    };
  }

  async exportToWord(content, filePath) {
    try {
      const doc = this.createDocument(content);
      const buffer = await Packer.toBuffer(doc);
      
      fs.writeFileSync(filePath, buffer);
      return { success: true, filePath };
    } catch (error) {
      console.error('导出Word文档失败:', error);
      throw new Error('导出Word文档失败');
    }
  }

  createDocument(content) {
    const { title, content: articleContent } = content;
    
    const children = [];
    
    // 添加标题
    children.push(
      new Paragraph({
        children: [
          new TextRun({
            text: title,
            bold: true,
            size: 32, // 16pt
            font: this.defaultStyles.font
          })
        ],
        heading: HeadingLevel.TITLE,
        alignment: AlignmentType.CENTER,
        spacing: {
          after: 400
        }
      })
    );

    // 解析并添加内容
    const contentElements = this.parseContent(articleContent);
    children.push(...contentElements);

    return new Document({
      sections: [{
        properties: {},
        children: children
      }],
      styles: {
        default: {
          document: {
            run: {
              font: this.defaultStyles.font,
              size: this.defaultStyles.fontSize
            },
            paragraph: {
              spacing: {
                line: this.defaultStyles.lineSpacing,
                after: this.defaultStyles.paragraphSpacing
              }
            }
          }
        }
      }
    });
  }

  parseContent(htmlContent) {
    const elements = [];
    
    // 简单的HTML解析，将HTML转换为docx元素
    const lines = htmlContent.split('\n').filter(line => line.trim());
    
    for (const line of lines) {
      const trimmed = line.trim();
      
      if (trimmed.startsWith('<h1>') || trimmed.startsWith('<h2>') || trimmed.startsWith('<h3>')) {
        // 处理标题
        const level = parseInt(trimmed.charAt(2));
        const text = this.stripHtml(trimmed);
        
        elements.push(
          new Paragraph({
            children: [
              new TextRun({
                text: text,
                bold: true,
                size: level === 1 ? 28 : level === 2 ? 26 : 24,
                font: this.defaultStyles.font
              })
            ],
            heading: level === 1 ? HeadingLevel.HEADING_1 : 
                    level === 2 ? HeadingLevel.HEADING_2 : HeadingLevel.HEADING_3,
            spacing: {
              before: 300,
              after: 200
            }
          })
        );
      } else if (trimmed.startsWith('<pre><code')) {
        // 处理代码块
        const codeText = this.extractCodeText(trimmed);
        elements.push(
          new Paragraph({
            children: [
              new TextRun({
                text: codeText,
                font: 'Consolas',
                size: 20,
                color: '333333'
              })
            ],
            shading: {
              fill: 'F5F5F5'
            },
            spacing: {
              before: 200,
              after: 200
            },
            indent: {
              left: 400
            }
          })
        );
      } else if (trimmed.startsWith('<p>')) {
        // 处理段落
        const paragraphRuns = this.parseInlineElements(trimmed);
        
        elements.push(
          new Paragraph({
            children: paragraphRuns,
            spacing: {
              after: this.defaultStyles.paragraphSpacing
            }
          })
        );
      } else if (trimmed && !trimmed.startsWith('<')) {
        // 处理纯文本段落
        elements.push(
          new Paragraph({
            children: [
              new TextRun({
                text: trimmed,
                font: this.defaultStyles.font,
                size: this.defaultStyles.fontSize
              })
            ],
            spacing: {
              after: this.defaultStyles.paragraphSpacing
            }
          })
        );
      }
    }
    
    return elements;
  }

  parseInlineElements(htmlText) {
    const runs = [];
    let currentText = this.stripHtml(htmlText);
    
    // 简单处理粗体和斜体
    const boldRegex = /<strong>(.*?)<\/strong>/g;
    const italicRegex = /<em>(.*?)<\/em>/g;
    const codeRegex = /<code>(.*?)<\/code>/g;
    
    // 这里简化处理，实际应该更复杂的解析
    currentText = currentText.replace(boldRegex, (match, text) => {
      runs.push(new TextRun({
        text: text,
        bold: true,
        font: this.defaultStyles.font,
        size: this.defaultStyles.fontSize
      }));
      return '';
    });
    
    currentText = currentText.replace(italicRegex, (match, text) => {
      runs.push(new TextRun({
        text: text,
        italics: true,
        font: this.defaultStyles.font,
        size: this.defaultStyles.fontSize
      }));
      return '';
    });
    
    currentText = currentText.replace(codeRegex, (match, text) => {
      runs.push(new TextRun({
        text: text,
        font: 'Consolas',
        size: 20,
        shading: {
          fill: 'F0F0F0'
        }
      }));
      return '';
    });
    
    // 添加剩余文本
    if (currentText.trim()) {
      runs.push(new TextRun({
        text: currentText.trim(),
        font: this.defaultStyles.font,
        size: this.defaultStyles.fontSize
      }));
    }
    
    return runs.length > 0 ? runs : [
      new TextRun({
        text: this.stripHtml(htmlText),
        font: this.defaultStyles.font,
        size: this.defaultStyles.fontSize
      })
    ];
  }

  stripHtml(html) {
    return html.replace(/<[^>]*>/g, '').trim();
  }

  extractCodeText(codeHtml) {
    const match = codeHtml.match(/<code[^>]*>([\s\S]*?)<\/code>/);
    return match ? match[1].trim() : '';
  }

  // 预设模板方法
  createTemplate(templateType = 'default') {
    const templates = {
      default: {
        title: '技术文章标题',
        sections: [
          '## 引言',
          '在这里介绍文章的背景和重要性...',
          '## 核心内容',
          '详细阐述技术要点...',
          '```javascript\n// 代码示例\nconsole.log("Hello World");\n```',
          '## 总结',
          '总结文章要点和后续建议...'
        ]
      },
      tutorial: {
        title: '技术教程：[技术名称]入门指南',
        sections: [
          '## 前言',
          '## 环境准备',
          '## 基础概念',
          '## 实践操作',
          '## 常见问题',
          '## 总结与进阶'
        ]
      }
    };
    
    return templates[templateType] || templates.default;
  }
}

module.exports = DocumentExporter;